package io.renren.modules.noc.controller;

import io.renren.common.sms.AliyunSms;
import io.renren.common.sms.YxuntongSms;
import io.renren.common.utils.GlobalConstant;
import io.renren.common.utils.MemberQRCodeUtil;
import io.renren.common.utils.R;
import io.renren.modules.noc.entity.*;
import io.renren.modules.noc.service.*;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.shiro.ShiroUtils;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseController extends AbstractController {
    @Autowired
    private NocTemplateService nocTemplateService;
    @Autowired
    private NocMemberService nocMemberService;
    @Autowired
    private NocLyService nocLyService;
    @Autowired
    private NocBusinessService nocBusinessService;
    @Autowired
    private NocBeerTicketMemberService nocBeerTicketMemberService;
    @Autowired
    private NocBeerTicketBusinessService nocBeerTicketBusinessService;
    @Autowired
    private MemberQRCodeUtil memberQRCodeUtil;

    @Value("${ercode.pre}")
    private String _pre;
    @Value("${ercode.busiPre}")
    private String _busiPre;

    @Value("${sms.aliyun.checkCode.signName}")
    private String smsSignName;
    @Value("${sms.aliyun.checkCode.template}")
    private String smsTemplate;

    /**
     * 获取默认的活动
     * @return
     */
    public Integer getDefaultTemplateId(){
        Map<String, Object> p = new HashMap<>();
        p.put("is_default","1");
        List<NocTemplateEntity> list = (List<NocTemplateEntity>) nocTemplateService.listByMap(p);
        if(list!=null&&list.size()>0){
            NocTemplateEntity nocTemplateEntity = list.get(0);
            ShiroUtils.getSession().setAttribute("template",nocTemplateEntity);
            return nocTemplateEntity.getId();
        }
        return null;
    }

    /**
     * 获取默认展会ID
     * @return
     */
    public Integer getDefaultTemplateIdNosession(){
        Map<String, Object> p = new HashMap<>();
        p.put("is_default","1");
        List<NocTemplateEntity> list = (List<NocTemplateEntity>) nocTemplateService.listByMap(p);
        if(list!=null&&list.size()>0){
            NocTemplateEntity nocTemplateEntity = list.get(0);
            //ShiroUtils.getSession().setAttribute("template",nocTemplateEntity);
            return nocTemplateEntity.getId();
        }
        return null;
    }

    /**
     * 根据二维码获取展会id
     * @param barCode
     * @return
     */
    public Integer getTidByBarCode(String barCode){
        Map<String, Integer> map =nocMemberService.getMemberTid(barCode);
        return map.get("tid");
    }

    public Session getSession(){
        Session session = ShiroUtils.getSession();
        session.setTimeout(60*60*1000);
        return session;
    }

    //判断用户是否存在
    public NocMemberEntity userIsExit(String mobile,String tid){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("col1",mobile);
        map.put("tid",tid);
        List<NocMemberEntity> list = (List<NocMemberEntity>)nocMemberService.listByMap(map);
        if(list!=null&&list.size()>0){
            return list.get(0);
        }
        return null;
    }

    //生成二维码 - 观众
    public String getNextErCode(){
//        String ercode = nocMemberService.getNextErCode(_pre);
//        if(StringUtils.isNotEmpty(ercode)){
//            return _pre+ercode;
//        }else{
//            return _pre+"000001";
//        }
        String memberQRCode = memberQRCodeUtil.getMemberQRCode(_pre);
        return memberQRCode;

    }

    //生成二维码 - 展商
    public String getNextErCodeBusi(){
        String ercode = nocBusinessService.getNextErCode(_busiPre);
        if(StringUtils.isNotEmpty(ercode)){
            return _busiPre+ercode;
        }else{
            return _busiPre+"000001";
        }
    }
    //生成啤酒节二维码展商
    public String getNextErCodeBeer(){
        String ercode = nocBeerTicketBusinessService.getNextErCode(_busiPre);
        if(StringUtils.isNotEmpty(ercode)){
            return _busiPre+ercode;
        }else{
            return _busiPre+"000001";
        }
    }

    /**
     * 判断是否是vip
     * @param ly  来源
     * @param tid 展会
     * @return 1是会员  0非会员
     */
    public String isCreateVipMember(String ly,String tid){
        Map<String,Object> p = new HashMap<>();
        p.put("ly",ly);
        p.put("tid",tid);
        List<NocLyEntity> lyList = (List<NocLyEntity>) nocLyService.listByMap(p);
        if(lyList!=null&&lyList.size()>0){
            NocLyEntity nocLyEntity = lyList.get(0);
            String isVip = nocLyEntity.getIsVip();
            if("1".equals(isVip)){
                return "1";
            }else{
                return "0";
            }
        }
        return "0";
    }

    /**
     * member绑定openid - 观众
     * @param memberId
     */
    public void memberAddOpenId(Integer memberId){
        Session session = this.getSession();
        Map wxUser = (HashMap)session.getAttribute(GlobalConstant.SESSION_WX_USER);
        if(wxUser!=null){
            NocMemberEntity mbOpenId = new NocMemberEntity();
            mbOpenId.setId(memberId);
            mbOpenId.setOpenId((String)wxUser.get("openId"));
            nocMemberService.updateById(mbOpenId);
        }
    }

    /**
     * member绑定openid - 展商
     * @param businessId
     */
    public void businessAddOpenId(Integer businessId){
        Session session = this.getSession();
        Map wxUser = (HashMap)session.getAttribute(GlobalConstant.SESSION_WX_USER);
        if(wxUser!=null){
            NocBusinessEntity mbOpenId = new NocBusinessEntity();
            mbOpenId.setId(businessId);
            mbOpenId.setOpenId((String)wxUser.get("openId"));
            nocBusinessService.updateById(mbOpenId);
        }
    }

    /**
     * member绑定openid - 啤酒节(观众)
     * @param ticketId
     */
    public void beerMemberAddOpenId(Integer ticketId){
        Session session = this.getSession();
        Map wxUser = (HashMap)session.getAttribute(GlobalConstant.SESSION_WX_USER);
        if(wxUser!=null){
            NocBeerTicketMemberEntity mbOpenId = new NocBeerTicketMemberEntity();
            mbOpenId.setId(ticketId);
            mbOpenId.setOpenId((String)wxUser.get("openId"));
            nocBeerTicketMemberService.updateById(mbOpenId);
        }
    }

    /**
     * member绑定openid - 啤酒节(展商)
     * @param ticketId
     */
    public void beerBusinessAddOpenId(Integer ticketId){
        Session session = this.getSession();
        Map wxUser = (HashMap)session.getAttribute(GlobalConstant.SESSION_WX_USER);
        if(wxUser!=null){
            NocBeerTicketBusinessEntity mbOpenId = new NocBeerTicketBusinessEntity();
            mbOpenId.setId(ticketId);
            mbOpenId.setOpenId((String)wxUser.get("openId"));
            nocBeerTicketBusinessService.updateById(mbOpenId);
        }
    }

    /**
     * 查询同行人员-观众
     * @param tid
     * @param memberId
     * @return
     */
    public void memberTongx(String tid,Integer memberId,HttpServletRequest req){
        Map<String,Object> p = new HashMap<>();
        p.put("txid",memberId);
        p.put("tid",tid);
        List<NocMemberEntity> list = (List<NocMemberEntity>) nocMemberService.listByMap(p);
        int count = 1;
        String li = "";
        for(NocMemberEntity member:list){
            String margin = "";
            if(count>1){
                margin = "margin-top:16px;";
            }
            li += "<div id='tx" + count + "'>";
            li += " <li style='position:relative;"+margin+"'><span>同行人员" + count + "*：</span> <input type='text' style='width:60%;' class='txt' name='names' value='"+member.getCol3()+"' id='name" + count + "' placeholder='姓名'>";
            li += "     <label style='position:absolute;top:75%;padding-left: 10px;' onclick='javascript:delTongxing(" + count + ");'><img src='/statics/js/modules/h5/images/del.png' width='25' height='25'/></label></li>";
            li += " <li ><span>&nbsp;</span> <input type='text' class='txt' style='width:60%;' name='mobiles' value='"+member.getCol1()+"' id='mobile" + count + "' placeholder='手机号'></li>";
            li += "</div>";
            count++;
        }
        req.setAttribute("tongxing",li);
        req.setAttribute("txCount",count);
    }

    /**
     * 查询同行人员-展商
     * @param tid
     * @param businessId
     * @return
     */
    public void businessTongx(String tid,Integer businessId,HttpServletRequest req){
        Map<String,Object> p = new HashMap<>();
        p.put("txid",businessId);
        p.put("tid",tid);
        List<NocBusinessEntity> list = (List<NocBusinessEntity>) nocBusinessService.listByMap(p);
        int count = 1;
        String li = "";
        for(NocBusinessEntity business:list){
            String margin = "";
            if(count>1){
                margin = "margin-top:16px;";
            }
            li += "<div id='tx" + count + "'>";
            li += " <li style='position:relative;"+margin+"'><span>同行人员" + count + "*：</span> <input type='text' style='width:60%;' class='txt' name='names' value='"+business.getName()+"' id='name" + count + "' placeholder='姓名'>";
            li += "     <label style='position:absolute;top:75%;padding-left: 10px;' data-id='"+business.getId()+"' onclick='javascript:delTongxing(this," + count + ");'><img src='/statics/js/modules/h5/images/del.png' width='25' height='25'/></label></li>";
            li += " <li ><span>&nbsp;</span> <input type='text' class='txt' style='width:60%;' name='mobiles' value='"+business.getMobile()+"' id='mobile" + count + "' placeholder='手机号'></li>";
            li += "</div>";
            count++;
        }
        req.setAttribute("tongxing",li);
        req.setAttribute("txCount",count);
    }


    /**
     * 查询展商发的门票
     * @param tid
     * @param businessId
     * @return
     */
    public void beerTongx(String tid,Integer businessId,String validDate,HttpServletRequest req){
        Map<String,Object> p = new HashMap<>();
        p.put("business_id",businessId);
        p.put("tid",tid);
        p.put("valid_date",validDate);
        List<NocBeerTicketBusinessEntity> list = (List<NocBeerTicketBusinessEntity>) nocBeerTicketBusinessService.listByMap(p);
        int count = 1;
        String li = "";
        for(NocBeerTicketBusinessEntity ticket:list){
            String margin = "";
            if(count>1){
                margin = "margin-top:16px;";
            }
            li += "<div id='tx" + count + "'>";
            li += " <li style='position:relative;"+margin+"'><span>人员" + count + "*：</span> <input type='text' style='width:60%;' class='txt' name='names' value='"+ticket.getName()+"' id='name" + count + "' placeholder='姓名' disabled>";
            li += "     <label style='position:absolute;top:75%;padding-left: 10px;' data-id='"+ticket.getId()+"' onclick='javascript:delTongxing(this," + count + ");'><img src='/statics/js/modules/h5/images/del.png' width='25' height='25'/></label></li>";
            li += " <li ><span>&nbsp;</span> <input type='text' class='txt' style='width:60%;' name='mobiles' value='"+ticket.getMobile()+"' id='mobile" + count + "' placeholder='手机号'  disabled></li>";
            li += "</div>";
            count++;
        }
        req.setAttribute("tongxing",li);
        req.setAttribute("txCount",count);
    }

    /**
     *  短信验证码发送  - 阿里云
     * @param mobile
     */
    public String sendCheckCode(String tid,String mobile){
        NocTemplateEntity template = nocTemplateService.getById(tid);
        if(template!=null && StringUtils.isNotEmpty(template.getMsgAccout())){
            String msgAccount = template.getMsgAccout();
            String msgPwd = template.getMsgPwd();
            return AliyunSms.sendCheckCode(msgAccount, msgPwd, mobile, smsSignName, smsTemplate);
        }else{
            return null;
        }
    }

    /**
     * 发送通知短信
     * @param tid
     * @param mobile
     * @param signName
     * @param code
     * @param paramsJson
     */
    public void sendTzMsg(String tid,String mobile,String signName,String code,String paramsJson) {
        NocTemplateEntity template = nocTemplateService.getById(tid);
        if (template != null && StringUtils.isNotEmpty(template.getMsgyxAccount())) {
            String msgAccount = template.getMsgyxAccount();
            String msgPwd = template.getMsgyxPwd();
            //String account, String password, String phones, String signName, String templateCode, String json
            AliyunSms.sendMsg(msgAccount,msgPwd,mobile,signName,code,paramsJson);
        }
    }


    /**
     * 发送营销短信 - 优讯通
     * @param tid
     * @param mobile
     * @return
     */
    public void sendContentMsg(String tid,String mobile,String content) {
        NocTemplateEntity template = nocTemplateService.getById(tid);
        if (template != null && StringUtils.isNotEmpty(template.getMsgyxAccount())) {
            String msgYxAccount = template.getMsgyxAccount();
            String msgYxPwd = template.getMsgyxPwd();
            content += " 回T退";
            YxuntongSms.sendMsg(msgYxAccount, msgYxPwd, mobile, content);
        }
    }

    /**
     * 短信验证码发送
     * @param tid
     * @param mobile
     * @return
     */
    public R checkCode(String tid, String mobile) {
        Session session = this.getSession();
        // 发送短信，获取短信验证码
        String checkCode = this.sendCheckCode(tid,mobile);
        if (StringUtils.isNotBlank(checkCode)) {
            // 将验证码放入缓存中
            session.setAttribute("checkCode",checkCode);
            return R.ok("短信发送成功");
        } else {
            return R.error("短信发送失败");
        }
    }

}
